/**
 * 前端性能优化脚本
 * 包含图片懒加载、防抖函数等基础优化功能
 */
(function() {
  'use strict';
  
  // 1. 图片懒加载实现
  function initLazyLoading() {
    // 检查浏览器是否支持 IntersectionObserver
    if ('IntersectionObserver' in window) {
      const lazyImages = document.querySelectorAll('img.lazy');
      
      const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            const img = entry.target;
            
            // 加载图片
            if (img.dataset.src) {
              img.src = img.dataset.src;
              img.classList.remove('lazy');
              img.classList.add('loaded');
              
              // 停止观察这个图片
              imageObserver.unobserve(img);
            }
          }
        });
      }, {
        // 提前50px开始加载
        rootMargin: '50px 0px',
        threshold: 0.01
      });
      
      lazyImages.forEach(img => imageObserver.observe(img));
    } else {
      // 降级处理：直接加载所有图片
      const lazyImages = document.querySelectorAll('img.lazy');
      lazyImages.forEach(img => {
        if (img.dataset.src) {
          img.src = img.dataset.src;
          img.classList.remove('lazy');
          img.classList.add('loaded');
        }
      });
    }
  }
  
  // 2. 防抖函数
  function debounce(func, wait, immediate) {
    let timeout;
    return function executedFunction(...args) {
      const later = () => {
        timeout = null;
        if (!immediate) func(...args);
      };
      const callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) func(...args);
    };
  }
  
  // 3. 节流函数
  function throttle(func, limit) {
    let inThrottle;
    return function(...args) {
      if (!inThrottle) {
        func.apply(this, args);
        inThrottle = true;
        setTimeout(() => inThrottle = false, limit);
      }
    };
  }
  
  // 4. 简单的缓存实现
  class SimpleCache {
    constructor(maxSize = 50) {
      this.cache = new Map();
      this.maxSize = maxSize;
    }
    
    get(key) {
      if (this.cache.has(key)) {
        // 移到最后（LRU策略）
        const value = this.cache.get(key);
        this.cache.delete(key);
        this.cache.set(key, value);
        return value;
      }
      return null;
    }
    
    set(key, value) {
      if (this.cache.has(key)) {
        this.cache.delete(key);
      } else if (this.cache.size >= this.maxSize) {
        // 删除最旧的项
        const firstKey = this.cache.keys().next().value;
        this.cache.delete(firstKey);
      }
      this.cache.set(key, value);
    }
    
    clear() {
      this.cache.clear();
    }
  }
  
  // 5. 性能监控
  function initPerformanceMonitoring() {
    // 只在支持的浏览器中运行
    if ('performance' in window && 'PerformanceObserver' in window) {
      try {
        // 监控页面加载性能
        new PerformanceObserver((list) => {
          for (const entry of list.getEntries()) {
            console.log(`${entry.name}: ${entry.startTime.toFixed(2)}ms`);
          }
        }).observe({entryTypes: ['paint']});
        
        // 监控资源加载
        new PerformanceObserver((list) => {
          for (const entry of list.getEntries()) {
            if (entry.duration > 1000) { // 只记录加载时间超过1秒的资源
              console.warn(`慢资源: ${entry.name} - ${entry.duration.toFixed(2)}ms`);
            }
          }
        }).observe({entryTypes: ['resource']});
      } catch (e) {
        console.log('性能监控初始化失败:', e);
      }
    }
  }
  
  // 6. 初始化所有优化功能
  function init() {
    initLazyLoading();
    initPerformanceMonitoring();
    
    console.log('性能优化脚本已加载');
  }
  
  // 7. 导出到全局对象
  window.PerformanceUtils = {
    debounce,
    throttle,
    SimpleCache,
    initLazyLoading
  };
  
  // 8. DOM加载完成后初始化
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
  
})();